package com.psa.tool.net;

import android.util.Log;
import com.psa.element.IJson;
import com.psa.element.ISqlObject;
import com.psa.element.RequestCmd;
import com.psa.element.RequestMessage;
import com.psa.system.R;
import com.psa.tool.*;
import com.wxw.BaseLibrary.tool.L;

import java.lang.reflect.Type;
import java.util.List;

/**
 *
 * @author david
 * @date 14-3-12
 */
public class DataUpdater<T extends ISqlObject> implements IHttpCallback {
    private IGeneralEventCallback OnUpdatingListener;
    private IGeneralEventCallback OnUpdateCompletedListener;
    private T defClass = null;
    private RequestMessage requestMessage = null;

//    private String WSName = "MBAData";          //DataService.svc  MBAData
//    private String WSPostMethod = "getData";      //getdatabypost     getData
//    private String WSGetMethod = "getbasedata";         //getbasedata

    public T getDefClass() {
        return defClass;
    }

    public void setDefClass(T defClass) {
        this.defClass = defClass;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    private Type type = null;
    private boolean clearDB = false;

    public List<T> getData() {
        return data;
    }

    private List<T> data = null;

    public boolean isClearDB() {
        return clearDB;
    }

    public void setClearDB(boolean clearDB) {
        this.clearDB = clearDB;
    }

    public DataUpdater(Type type){
        this.type = type;
    }

    public DataUpdater(Type type, T defT){
        this(type);
        defClass = defT;
    }

    public void setOnUpdatingListener(IGeneralEventCallback onUpdatingListener) {
        OnUpdatingListener = onUpdatingListener;
    }

    public void setOnUpdateCompletedListener(IGeneralEventCallback onUpdateCompletedListener) {
        OnUpdateCompletedListener = onUpdateCompletedListener;
    }

    public void cancel(){
        if (requestMessage!=null) {
            requestMessage.Cancel=true;
        }
    }

    public void getBaseData(String sql){
        try{
            sql = sql.replace(" ", "|");
            String method = defClass==null?"execsql":defClass.getSyncMethod();
            RequestMessage requestMessage = new RequestMessage(SystemStatus.DATA_URL, SystemStatus.DataWSMethod,RequestCmd.create(method, sql), RequestCmd.class, this);
            RequestManager.getRequestManager().addMessage(requestMessage);
        } catch (Exception e){
            e.printStackTrace();
            Log.e(SystemStatus.TAG, "Class:DataUpdater,Msg:"+e.getMessage());
            triggerEvent(e.getMessage());
        }
    }

    public void getBaseDataByPost(String sql){
        try{
            String method = defClass==null?"execsql":defClass.getSyncMethod();
            requestMessage = new RequestMessage(SystemStatus.DATA_URL, SystemStatus.DataWSMethod,RequestCmd.create(method, sql), RequestCmd.class, this, RequestMessage.HTTP_METHOD.POST);
            RequestManager.getRequestManager().addMessage(requestMessage);
        } catch (Exception e){
            e.printStackTrace();
            Log.e(SystemStatus.TAG, "Class:DataUpdater,Msg:"+e.getMessage());
            triggerEvent(e.getMessage());
        }
    }

    public void getBaseDataByPost(){
        if (defClass==null) {
            return;
        }
        getBaseDataByPost(defClass.getDataSql());
    }

    public void getBaseData(RequestCmd cmd){
        try{
            RequestMessage<RequestCmd> requestMessage = new RequestMessage<RequestCmd>(SystemStatus.DATA_URL, SystemStatus.DataWSMethod, cmd, RequestCmd.class, this);
            RequestManager.getRequestManager().addMessage(requestMessage);
        } catch (Exception e){
            e.printStackTrace();
            Log.e(SystemStatus.TAG, "Class:DataUpdater,Msg:"+e.getMessage());
            triggerEvent(e.getMessage());
        }
    }

    public void getBaseDataByPost(RequestCmd cmd){
        try{
            RequestMessage<RequestCmd> requestMessage = new RequestMessage<RequestCmd>(SystemStatus.DATA_URL, SystemStatus.DataWSMethod, cmd, RequestCmd.class, this, RequestMessage.HTTP_METHOD.POST);
            RequestManager.getRequestManager().addMessage(requestMessage);
        } catch (Exception e){
            e.printStackTrace();
            Log.e(SystemStatus.TAG, "Class:DataUpdater,Msg:"+e.getMessage());
            triggerEvent(e.getMessage());
        }
    }

    private void importData(String jsonData){
        try{
            data = SystemTool.getJsonObjs(jsonData, type);
            if (data == null || data.size()<=0) {
                triggerEvent(SystemStatus.MainActivity.getString(R.string.dataupdater_datatable) + type.toString() + SystemStatus.MainActivity.getString(R.string.dataupdater_err)
                        +"\n"+ SystemStatus.MainActivity.getString(R.string.app_data_content)+ jsonData);
                triggerCompletedEvent(this, "");
                return;
            }
            if (data.size()>0 && clearDB){
                data.get(0).clear(DBTool.getInstance());
            }
            String tbname = data.get(0).getClass().getSimpleName();
            int i = 0;
            for (T tt : data) {
                tt.insert(DBTool.getInstance());
                i++;
            }
            triggerEvent(this, SystemStatus.MainActivity.getString(R.string.dataupdater_datatable) + tbname + SystemStatus.MainActivity.getString(R.string.dataupdater_text1) + i
                + SystemStatus.MainActivity.getString(R.string.dataupdater_text2));
        } catch (Exception e){
            triggerCompletedEvent(this, "importData exception:" + e.getMessage()+",ObjectType:"+type.toString()+",jsonData:"+jsonData);
        }
        triggerCompletedEvent(this, "");
    }

    private void triggerEvent(String content){
        triggerEvent(this, content);
    }

    private void triggerEvent(Object sender, String content){
        try {
            if (OnUpdatingListener != null) {
                OnUpdatingListener.finished(sender, content);
            }
        } catch (Exception e) {
            L.WriteExceptionLog("DataUpdater", "triggerEvent", e.getMessage());
        }
    }

    private void triggerCompletedEvent(Object sender, String content) {
        try {
            if (OnUpdateCompletedListener != null) {
                OnUpdateCompletedListener.finished(sender, content);
            }
        } catch (Exception e) {
            L.WriteExceptionLog("DataUpdater", "triggerCompletedEvent", e.getMessage());
        }
    }

    @Override
    public void callCompleted(RequestMessage message, IJson requestCmd) {
        try {
            importData(((RequestCmd) requestCmd).Result);
        } catch (Exception e) {
            triggerCompletedEvent(this, "DataUpdater callCompleted exception:" + e.getMessage());
        }
    }

    @Override
    public void callError(RequestMessage message, String err) {
        try {
            SystemStatus.showMessage(SystemStatus.MainActivity, "DataUpdater callError:" + err);
        } catch (Exception e) {
            L.WriteExceptionLog("DataUpdater", "callError", e.getMessage());
        }
        triggerCompletedEvent(this, err);
    }
}
